package com.hqd.ch03.v27.spel.ast;

import com.hqd.ch03.v27.spel.standard.ExpressionState;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 方法节点
 */
public class MethodReference extends SpelNodeImpl {
    private final String name;

    public MethodReference(String methodName, int startPos, int endPos, SpelNodeImpl... args) {
        super(startPos, endPos, args);
        this.name = methodName;
    }

    @Override
    public Object getValue(ExpressionState state) {
        Object activeContextObject = state.getActiveContextObject();
        try {
            List<Object> params = new ArrayList<>();
            if (ArrayUtils.isNotEmpty(children)) {
                Arrays.stream(children).forEach(spelNode -> {
                    params.add(spelNode.getValue(state));
                });
            }
            return MethodUtils.invokeMethod(activeContextObject, name, params.toArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String getName() {
        return name;
    }
}
